package org.Yiran.timetale_re.client.gui.base;

import com.mojang.blaze3d.platform.Lighting;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import org.Yiran.timetale_re.item.runeblueprint.base.RuneBlueprintItem;
import org.jetbrains.annotations.NotNull;

/**
 * 符文雕刻屏幕
 * 用于在GUI中显示符文蓝图的3D模型，支持旋转和缩放功能
 */
public class RuneCarvingScreen extends Screen {
    
    // ==================== 常量定义 ====================
    
    /** GUI宽度 */
    protected static final int GUI_WIDTH = 200;
    
    /** GUI高度 */
    protected static final int GUI_HEIGHT = 140;
    
    /** 缩放增量 */
    private static final float SCALE_INCREMENT = 0.1f;
    
    /** 最小缩放比例 */
    private static final float MIN_SCALE = 0.5f;
    
    /** 最大缩放比例 */
    private static final float MAX_SCALE = 3.0f;

    // ==================== 实例变量 ====================

    /** 蓝图物品堆 */
    protected final ItemStack blueprintStack;
    
    /** 符文类型 */
    protected final String runeType;
    
    /** GUI左上角X坐标 */
    protected int guiLeft;
    
    /** GUI左上角Y坐标 */
    protected int guiTop;

    // ==================== 3D模型旋转相关变量 ====================
    
    /** X轴旋转角度 */
    private float rotationX = 0.0f;
    
    /** Y轴旋转角度 */
    private float rotationY = 0.0f;
    
    /** 上次X轴旋转角度 */
    private float lastRotationX = 0.0f;
    
    /** 上次Y轴旋转角度 */
    private float lastRotationY = 0.0f;

    // ==================== 缩放相关变量 ====================
    
    /** 缩放因子 */
    private float scaleFactor = 1.0f;

    // ==================== 鼠标拖拽相关变量 ====================
    
    /** 是否正在拖拽 */
    private boolean isDragging = false;
    
    /** 上次鼠标X坐标 */
    private int lastMouseX = 0;
    
    /** 上次鼠标Y坐标 */
    private int lastMouseY = 0;

    // ==================== 构造函数 ====================

    /**
     * 构造函数
     * @param blueprintStack 蓝图物品堆
     */
    public RuneCarvingScreen(ItemStack blueprintStack) {
        super(Component.translatable("screen.timetale_re.rune_carving"));
        this.blueprintStack = blueprintStack;
        this.runeType = RuneBlueprintItem.getRuneType(blueprintStack);
    }

    // ==================== 初始化方法 ====================

    @Override
    protected void init() {
        this.guiLeft = (this.width - GUI_WIDTH) / 2;
        this.guiTop = (this.height - GUI_HEIGHT) / 2;
    }

    // ==================== 关闭处理 ====================

    @Override
    public void onClose() {
        super.onClose();
        // 播放关闭GUI的翻书声
        if (Minecraft.getInstance().player != null) {
            Minecraft.getInstance().player.playSound(SoundEvents.BOOK_PAGE_TURN);
        }
    }

    // ==================== 渲染方法 ====================

    @Override
    public void render(@NotNull GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
        super.render(guiGraphics, mouseX, mouseY, partialTicks);

        // 渲染3D模型
        render3DModel(guiGraphics, mouseX, mouseY, partialTicks);
    }

    /**
     * 渲染3D模型
     * @param guiGraphics GUI图形对象
     * @param mouseX 鼠标X坐标
     * @param mouseY 鼠标Y坐标
     * @param partialTicks 部分刻度
     */
    private void render3DModel(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
        Lighting.setupForFlatItems();

        PoseStack poseStack = guiGraphics.pose();
        poseStack.pushPose();

        // 移动到屏幕中心
        poseStack.translate(width / 2.0f, height / 2.0f, 100.0f);

        // 应用缩放
        poseStack.scale(scaleFactor * 50, -scaleFactor * 50, scaleFactor * 50);

        // 应用旋转
        poseStack.mulPose(Axis.XP.rotationDegrees(rotationX));
        poseStack.mulPose(Axis.YP.rotationDegrees(rotationY));
        poseStack.mulPose(Axis.ZP.rotationDegrees(180));

        // 获取模型资源位置
        ResourceLocation modelLocation = ResourceLocation.fromNamespaceAndPath("timetale_re", "block/rune_blueprint/rune_blueprint_" + runeType);

        // 获取烘焙模型
        BakedModel model = Minecraft.getInstance().getModelManager().getModel(modelLocation);

        // 渲染模型
        MultiBufferSource.BufferSource bufferSource = Minecraft.getInstance().renderBuffers().bufferSource();
        Minecraft.getInstance().getItemRenderer().render(
                blueprintStack,
                ItemDisplayContext.GUI,
                false,
                poseStack,
                bufferSource,
                15728880,
                OverlayTexture.NO_OVERLAY,
                model
        );
        bufferSource.endBatch();

        poseStack.popPose();

        // 恢复2D渲染状态
        RenderSystem.enableDepthTest();
    }

    // ==================== 输入处理方法 ====================

    @Override
    public boolean mouseScrolled(double mouseX, double mouseY, double delta) {
        if (delta > 0) {
            this.scaleFactor = Math.min(this.scaleFactor + SCALE_INCREMENT, MAX_SCALE);
        } else if (delta < 0) {
            this.scaleFactor = Math.max(this.scaleFactor - SCALE_INCREMENT, MIN_SCALE);
        }
        return true;
    }

    @Override
    public boolean mouseDragged(double mouseX, double mouseY, int button, double dragX, double dragY) {
        if (button == 0) { // 左键拖拽旋转
            float deltaX = (float)(mouseX - lastMouseX);
            float deltaY = (float)(mouseY - lastMouseY);

            rotationY = lastRotationY + deltaX * 0.5f;
            rotationX = lastRotationX + deltaY * 0.5f;
            return true;
        }
        return super.mouseDragged(mouseX, mouseY, button, dragX, dragY);
    }

    @Override
    public boolean mouseClicked(double mouseX, double mouseY, int button) {
        if (button == 0) { // 左键按下
            this.isDragging = true;
            this.lastMouseX = (int)mouseX;
            this.lastMouseY = (int)mouseY;
            this.lastRotationX = rotationX;
            this.lastRotationY = rotationY;
            return true;
        }
        return super.mouseClicked(mouseX, mouseY, button);
    }

    @Override
    public boolean mouseReleased(double mouseX, double mouseY, int button) {
        if (button == 0) { // 左键释放
            this.isDragging = false;
            this.lastRotationX = rotationX;
            this.lastRotationY = rotationY;
            return true;
        }
        return super.mouseReleased(mouseX, mouseY, button);
    }

    // ==================== 其他方法 ====================

    @Override
    public boolean isPauseScreen() {
        return false; // 不暂停游戏
    }
}